<template>
  <div class="bank-container">
    <div class="page-content">
      <div class="bank-page">
        <!-- 面包屑导航区域 -->
        <div class="page-nav">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item @click="handleBack">
                <i class="fas fa-chevron-left"></i>
                {{ fromWithdraw ? $t('返回提款') : $t('返回账户') }}
              </el-breadcrumb-item>
              <el-breadcrumb-item>{{ $t('银行卡管理') }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="divider"></div>
        </div>

        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('银行卡管理') }}</h1>
          <div class="security-alert">
            <i class="fas fa-shield-alt"></i>
            {{ $t('为了您的资金安全，请仔细核对添加的银行卡信息') }}
          </div>
        </div>

        <!-- 添加银行卡按钮 -->
        <div class="action-bar" v-if="bankCards.length === 0">
          <el-button type="primary" class="amazon-button primary" @click="showAddCardModal = true">
            <i class="fas fa-plus"></i> {{ $t('添加银行卡') }}
          </el-button>
        </div>

        <!-- 银行卡列表 -->
        <div class="card-list">
          <div v-if="bankCards.length === 0" class="empty-state">
            <el-empty :image-size="120">
              <template #image>
                <i class="fas fa-credit-card empty-icon"></i>
              </template>
              <template #description>
                <p class="empty-text">{{ $t('暂无银行卡') }}</p>
              </template>
            </el-empty>
          </div>

          <div v-else v-for="card in bankCards" :key="card.id" class="bank-card">
            <div class="card-header">
              <!-- <img :src="getBankLogo(card.bankName)" :alt="card.bankName" class="bank-logo" /> -->
              <span class="bank-name">{{ card.bankName }}</span>
              <!-- <img :src="getCardTypeIcon(card.cardType)" :alt="getCardTypeLabel(card.cardType)"
                class="card-type-logo" /> -->
            </div>

            <div class="card-body">
              <div class="card-number">
                **** **** **** {{ card. bankCardNumber.slice(-4) }}
              </div>
              <div class="card-holder">{{ card.ownerName }}</div>
            </div>

            <div class="card-footer">
              <span class="default-tag" v-if="card.isDefault">{{ $t('默认卡片') }}</span>
              <div class="card-actions">
<!--                <el-button  type="text" @click="setshowAddCardModale(card)">-->
<!--                  {{ $t('编辑') }}-->
<!--                </el-button>-->
                <el-button type="text" class="delete-btn" @click="handleDelete(card)">
                  {{ $t('删除') }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页器 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <Footer />
    <AddBankCard v-model="showAddCardModal"   @submit="handleAddCard" />
    <UpdateBankCard v-model="showAddCardModal2" :carItem="carItem" @setAsDefault="setAsDefault" />
    <VerifyDialog v-model="showDeleteVerify" :title="$t('删除银行卡')" :warning-text="$t('删除银行卡需要验证，请选择验证方式')"
      :confirm-button-text="$t('确认删除')" confirm-button-type="danger" @confirm="handleDeleteConfirm"
      @cancel="showDeleteVerify = false" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import Footer from '@/components/Footer.vue'
import AddBankCard from './components/AddBankCard.vue'
import UpdateBankCard from './components/UpdateBankCard.vue'
import VerifyDialog from '@/components/VerifyDialog.vue'
import {  getbankList,bankUpdate, memberbanklistAdd ,bankDel} from '@/api/assets'
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const router = useRouter()
const route = useRoute()

// 判断是否从提款页面进入
const fromWithdraw = computed(() => route.query.from === 'withdraw')

// 银行卡列表
const bankCards = ref([])
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 银行列表
const carItem = ref({})

// 卡片类型列表
const cardTypes = []

// 表单相关
const showAddCardModal = ref(false)
const showAddCardModal2 = ref(false)
const showDeleteVerify = ref(false)
const cardToDelete = ref<number | null>(null)



// 获取银行卡列表
const getBankLogo = (bankName: string) => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }
  getbankList(params).then(res => {
    bankCards.value = res.rows;
    total.value = res.total
  })
  // const bank = bankList.find(b => b.name === bankName)
  // return bank?.logo || '/images/banks/default.png'
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
  getBankLogo();
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
  getBankLogo()
}

// 获取卡片类型图标
const getCardTypeIcon = (type: string) => {
  return cardTypes.find(t => t.value === type)?.icon
}

// 获取卡片类型标签
const getCardTypeLabel = (type: string) => {
  return cardTypes.find(t => t.value === type)?.label
}

// 添加银行卡
const handleAddCard = (newCard: any) => {
  console.log(newCard,'newCard');

  let obj = {
    // 银行卡号
    bankCardNumber: newCard.bankName,
    // 银行名称
    bankName: newCard.bankName,

    //备注
    // remark:newCard.remark,

    //持卡人姓名
    ownerName: newCard.ownerName,

    //是否为默认
    isDefault: newCard.isDefault,
  }

  memberbanklistAdd(newCard).then(res => {
    bankCards.value =  res.data;
    ElMessage.success(t('添加成功'))
    getBankLogo();
  })
  // if (newCard.isDefault) {
  //   bankCards.value.forEach(card => card.isDefault = false)
  // }


}
const setshowAddCardModale= (Card) => {
  console.log(Card,'Card');

  carItem.value = Card;
  console.log(carItem.value,'Card');

  showAddCardModal2.value = true;

}

// 编辑修改
const setAsDefault = (newCard) => {

  let obj = {
    id: newCard.id,
    // 银行卡号
    bankCardNumber: newCard.bankName,
    // 银行名称
    bankName: newCard.bankName,

    //备注
    remark:newCard.remark,

    //持卡人姓名
    ownerName: newCard.ownerName,

    //是否为默认
    isDefault: newCard.isDefault,
  }
  bankUpdate(newCard).then(res => {
    ElMessage.success(t('设置成功'))
    getBankLogo();
  })
}

// 删除银行卡
const handleDelete = (obj) => {
  // bankDel({id:obj.id}).then(res => {
  //   if(res.code == 200){
  //     ElMessage.success(t('设置成功'))
  //     getBankLogo();
  //   }
  // })
  cardToDelete.value = obj.id
  showDeleteVerify.value = true
}

// 实际删除卡片的API调用
const deleteCard = async (id: number | null, verifyType: string, verifyCode: string) => {
  if (!id) return
  // TODO: 调用删除API
  // console.log('删除卡片:', id, '验证方式:', verifyType, '验证码:', verifyCode)
  bankCards.value = bankCards.value.filter(card => card.id !== id)
}

// 验证通过后删除
const handleDeleteConfirm = async ({ type, code }: { type: string, code: string }) => {
  try {
    await bankDel({id:cardToDelete.value,code:code})
    ElMessage.success(t('删除成功'))
    showDeleteVerify.value = false
    cardToDelete.value = null
    // 重新获取列表
    await getBankLogo()
  } catch (error: any) {
    ElMessage.error(error.message || t('删除失败'))
  }
}

// 返回处理
const handleBack = () => {
  if (fromWithdraw.value) {
    router.push('/assets/bank-withdraw')
  } else {
    router.push('/account')
  }
}
onMounted(() => {
  getBankLogo();
})
</script>

<style lang="scss" scoped>
.bank-container {
  background-color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.bank-page {
  padding: 0;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.page-nav {
  margin-bottom: 16px;
  padding: 0 16px;
  background: #fff;

  .breadcrumb {
    margin-bottom: 12px;
    padding-top: 12px;

    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: #666;
        font-weight: normal;
        cursor: pointer;

        &:hover {
          color: #1890ff;
        }

        i {
          margin-right: 4px;
        }
      }
    }
  }

  .divider {
    height: 1px;
    background: #e8e8e8;
    margin: 0;
  }
}

.page-header {
  padding: 0 16px;
  font-size: 28px;
  color: #232f3e;
  font-weight: 400;
  margin-bottom: 16px;

  h1 {
    font-size: 24px;
    margin-bottom: 12px;
  }

  .security-alert {
    color: #0066c0;
    font-size: 14px;

    i {
      margin-right: 8px;
    }
  }
}

.action-bar {
  padding: 0 16px;
  margin-bottom: 16px;
}

.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 0 16px;
}
.pagination-wrapper {
  margin-top: 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: flex-end;
}

.bank-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .bank-logo {
      width: 32px;
      height: 32px;
      margin-right: 12px;
    }

    .bank-name {
      font-size: 16px;
      font-weight: 500;
      color: #232f3e;
    }

    .card-type-logo {
      width: 32px;
      height: 20px;
      object-fit: contain;
    }
  }

  .card-body {
    margin-bottom: 12px;

    .card-number {
      font-size: 18px;
      color: #232f3e;
      letter-spacing: 2px;
      margin-bottom: 8px;
    }

    .card-holder {
      font-size: 14px;
      color: #666;
    }
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .default-tag {
      font-size: 12px;
      color: #ff9900;
      background: #fff8e6;
      padding: 2px 8px;
      border-radius: 4px;
    }

    .card-actions {
      display: flex;
      gap: 12px;

      .delete-btn {
        color: #ff4d4f;
      }
    }
  }
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
}

.bank-option {
  display: flex;
  align-items: center;
  gap: 8px;

  .bank-logo-small {
    width: 24px;
    height: 24px;
  }
}

.card-type-option {
  display: flex;
  align-items: center;
  gap: 8px;

  .card-type-icon {
    width: 32px;
    height: 20px;
    object-fit: contain;
  }
}

@media (max-width: 768px) {
  .bank-page {
    padding: 0;
  }

  .card-list {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 0 12px;
  }

  .page-header {
    padding: 0 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    h1 {
      font-size: 20px;
    }
  }

  .page-nav,
  .action-bar {
    padding: 0 12px;
  }
}

:deep(.amazon-button) {
  &.primary {
    background: linear-gradient(to bottom, #f7dfa5, #f0c14b);
    border-color: #a88734 #9c7e31 #846a29;
    color: #111;

    &:hover {
      background: linear-gradient(to bottom, #f5d78e, #eeb933);
    }
  }
}

:deep(.el-empty) {
  padding: 60px 0;

  .empty-icon {
    font-size: 80px;
    color: #ccc;
    margin-bottom: 20px;
  }

  .empty-text {
    margin-top: 20px;
    color: #666;
    font-size: 14px;
  }
}
</style>
